//
//  THImageEditViewController.m
//  THImageEditDemo
//
//  Created by 希达 on 2018/3/27.
//  Copyright © 2018年 Tan.huang. All rights reserved.
//

#import "THImageEditViewController.h"
#import "THImageTool.h"
#import "THToolBase.h"
#import "THEditTool.h"
#import "THTitleView.h"
//#import <IQKeyboardManager/IQKeyboardManager.h>
//#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>
#import <TZImagePickerController/TZImagePickerController.h>
#import <YYKit/YYKit.h>

@interface THImageEditViewController ()

@property (weak, nonatomic) THTitleView *titleView;
@property (strong, nonatomic) THImageTool *imgTools;
@property (strong, nonatomic) THToolBase *currentTool;
@property (strong, nonatomic) UIImage *originalImage;
@end

@implementation THImageEditViewController



- (id)initWithImage:(UIImage *)image {
    self = [super init];
    if (self) {
        self.originalImage = image;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];

    [self configTitleView];
    [self configView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
//    self.fd_interactivePopDisabled = YES;
//    [IQKeyboardManager sharedManager].enable = NO;
//    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    self.fd_interactivePopDisabled = NO;
//    [IQKeyboardManager sharedManager].enable = YES;
//    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - setter
- (void)setTitleName:(NSString *)titleName {
    _titleName = titleName;
    self.titleView.title = titleName;
}

#pragma mark - config 
- (void)configTitleView {
    CGFloat height = TZCommonTools.tz_isIPhoneX ? 88 : 64;
    THTitleView *titleView = [[THTitleView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, height)];
    [self.view addSubview:titleView];
    self.titleView = titleView;

    @weakify(self);
    [titleView setTh_titleViewDoneClickBlock:^{
        @strongify(self);
        [self svaeImage];
    }];
}

- (void)configView {
    CGRect frame = self.view.frame;
    CGFloat bgHeight = (frame.size.width - 50) / 4 * 2 + 44 + 30 + (TZCommonTools.tz_isIPhoneX ? 34 : 0);
    CGFloat navigationBarMaxY = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, frame.size.height - bgHeight, frame.size.width, bgHeight)];
    self.bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bgView];

    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, navigationBarMaxY, frame.size.width, frame.size.height - self.bgView.frame.size.height - navigationBarMaxY)];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;

    [self.view addSubview:self.scrollView];
    
    self.imageView = [[UIImageView alloc] init];
//    self.imageView.backgroundColor = [UIColor whiteColor];
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    self.imageView.layer.masksToBounds = YES;
    self.imageView.image = self.originalImage;
    [self resetImageViewFrame];
    [self.scrollView addSubview:self.imageView];

    self.imgTools = [[THImageTool alloc] initWithFrame:self.bgView.bounds];
    self.imgTools.imageEditVC = self;
    self.imgTools.titleArray = [NSArray arrayWithObjects:@"Edit", @"Adjust", @"Layer", @"Add-ons", nil];
    self.imgTools.imageArray = [NSArray arrayWithObjects:@"edit", @"photo_editor", @"layers", @"rabbit_in_hat", nil];
    [self.imgTools configView];
    [self.bgView addSubview:self.imgTools];

    @weakify(self);
    self.imgTools.btnClickBlock = ^(NSString *title, BOOL isSelect) {
        @strongify(self);
        if ([title isEqualToString:@"Layer"]) {
            return ;
        }
        [self toolsTransformIsShow:NO];
        self.titleName = title;
        [self configTools:title];
    };
}

- (void)toolsTransformIsShow:(BOOL)isShow {
    if (isShow) {
        [UIView animateWithDuration:kTHImageToolAnimationDuration animations:^{
            self.imgTools.alpha = 1;
        }];
    } else {
        [UIView animateWithDuration:kTHImageToolAnimationDuration animations:^{
            self.imgTools.alpha = 0;
        }];
    }
    self.titleView.isShowDone = !self.imgTools.alpha;
}


- (void)refreshTool {
    [self.currentTool cleanup];
    [self toolsTransformIsShow:YES];
}


- (void)resetImageViewFrame
{
    CGSize size = (_imageView.image) ? _imageView.image.size : _imageView.frame.size;
    if(size.width>0 && size.height>0){
        self.ratio = MIN(self.scrollView.frame.size.width / size.width, self.scrollView.frame.size.height / size.height);
        CGFloat W = self.ratio * size.width;
        CGFloat H = self.ratio * size.height;

        _imageView.frame = CGRectMake(MAX(0, (self.scrollView.frame.size.width-W)/2), MAX(0, (self.scrollView.frame.size.height-H)/2), W, H);
    }
}

- (void)configTools:(NSString *)title {
    NSMutableString *mutableTitle = [NSMutableString stringWithString:title];
    [mutableTitle insertString:@"TH" atIndex:0] ;
    [mutableTitle appendString:@"Tool"];
    if ([mutableTitle containsString:@"-"]) {
        mutableTitle = [mutableTitle stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    self.currentTool = [[NSClassFromString(mutableTitle) alloc] initWithImageEditor:self];
    [self.currentTool setBgImage:[UIImage imageNamed:@"bg"]];
    if (self.filterArray) {
        self.currentTool.filterArray = self.filterArray;
    }
    if (self.picture) {
        self.currentTool.picture = self.picture;
    }
    
    [self.currentTool setup];
}


//- (void)config {
//    CubeMap myCube = createCubeMap(self.slider1.value, self.slider2.value);
//
//    NSData *myData = [[NSData alloc]initWithBytesNoCopy:myCube.data length:myCube.length freeWhenDone:true];
//
//    CIFilter *colorCubeFilter = [CIFilter filterWithName:@CIColorCube];
//
//    [colorCubeFilter setValue:[NSNumber numberWithFloat:myCube.dimension] forKey:@inputCubeDimension];
//
//    [colorCubeFilter setValue:myData forKey:@inputCubeData];
//
//    [colorCubeFilter setValue:[CIImage imageWithCGImage:_preview.image.CGImage] forKey:kCIInputImageKey];
//
//
//
//    CIImage *outputImage = colorCubeFilter.outputImage;
//
//    CIFilter *sourceOverCompositingFilter = [CIFilter filterWithName:@CISourceOverCompositing];
//
//    [sourceOverCompositingFilter setValue:outputImage forKey:kCIInputImageKey];
//
//    [sourceOverCompositingFilter setValue:[CIImage imageWithCGImage:backgroundImage.CGImage] forKey:kCIInputBackgroundImageKey];
//
//
//
//    outputImage = sourceOverCompositingFilter.outputImage;
//
//    CGImage *cgImage = [[CIContext contextWithOptions: nil]createCGImage:outputImage fromRect:outputImage.extent];
//}

//获取屏幕截屏方法
- (UIImage *)capture:(UIView *)view {
    // 创建一个context
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
    //把当前的全部画面导入到栈顶context中并进行渲染
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    // 从当前context中创建一个新图片
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    return img;
}


- (void)svaeImage {
    if ([self.originalImage isEqual:self.imageView.image]) {
        [self.navigationController popViewControllerAnimated:YES];
        if (self.th_imageEditViewControllerDoneClickBlock) {
            self.th_imageEditViewControllerDoneClickBlock(nil);
        }
        return;
    }

//    [self showTextHUDWithPleaseWait];

    NSData *imageData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;;
//        path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"imgs_%@",[UserDefautManager manager].userName]];
        path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"imgs_%@",@"tanhuang"]];
        if([[NSFileManager defaultManager] fileExistsAtPath:path]){
            NSMutableArray *imgs = [NSMutableArray arrayWithContentsOfFile:path];
            [imgs addObject:imageData];
            [imgs writeToFile:path atomically:YES];
        } else {
            NSMutableArray *imgs = [NSMutableArray array];
            [imgs addObject:imageData];
            [imgs writeToFile:path atomically:YES];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
//            [self hideTextHud];

            [self.navigationController popViewControllerAnimated:YES];
            if (self.th_imageEditViewControllerDoneClickBlock) {
                self.th_imageEditViewControllerDoneClickBlock(self.imageView.image);
            }
        });
    });
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
